﻿using CinemaMaestro.BusinessLayer.Contracts;
using CinemaMaestro.Common.IocContainer;
using CinemaMaestro.DataLayer.Contracts.Entities;
using CinemaMaestro.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CinemaMaestro.WebApi.Controllers
{
    public class CategoriesController : ApiController
    {

        [HttpGet]
        public IHttpActionResult GetAllCategories()
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();

            var list = businessUoW.Categories.Read().ToList();

            List<CategoryViewModel> models = new List<CategoryViewModel>();

            foreach (var model in list)
            {
                CategoryViewModel category = model;
                models.Add(category);
            }

            return Ok(models);
        }

        [HttpGet]
        public IHttpActionResult GetCategory(int id)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();

            var category = businessUoW.Categories.Read().FirstOrDefault(x => x.Id == id);
            if (category == null)
            {
                return NotFound();
            }
            CategoryViewModel categoryVM = category;
            return Ok(categoryVM);
        }

        [HttpPut]
        public IHttpActionResult UpdateCategory(CategoryViewModel categoryVM)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();
            Category category = categoryVM;
            businessUoW.Categories.Update(category);
            return Ok();
        }

        [HttpDelete]
        public IHttpActionResult DeleteCategory(int id)
        {
            var businessUow = Resolver.Get<IBusinessObjectFactory>();
            var hasDependencies = businessUow.Movies.MovieHasRelationWithCategory(id);
            if (hasDependencies)
            {
                return NotFound();
            }
            var deleted = businessUow.Categories.Delete(id);
            if (deleted)
            {
                return Ok();
            }
            return NotFound();
        }

        [HttpPost]
        public IHttpActionResult CreateCategory(CategoryViewModel categoryVM)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();
            Category category = categoryVM;
            businessUoW.Categories.Create(category);
            return Ok();
        }

    }
}
